<template>
  <div style="width: 100%" v-if="action === 'edit'">
    <div ref="gaode_Map" id="gaode_Map"></div>
  </div>
  <div id="container"></div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
// import { AddCompanyInfo, GetCompanyById } from '@/api/user'
import { useUserStore } from '@/stores/user'

const emit = defineEmits(['success'])

const props = {
  action: {
    type: String,
    default: 'edit',
  },
  companyId: {
    type: String,
    default: '',
  },
  longitude: {
    default: null,
  },
  latitude: {
    default: null,
  },
}

const map = ref(null) // 地图对象
const marker = ref(null) // 标记对象
const loaded = ref(false)
const infoWindow = ref(null) // 弹窗对象
const auto = ref(null)
const placeSearch = ref(null)
const id = ref(null)
const myForm = reactive({
  address: null,
  longitude: null,
  latitude: null,
  coordinate: '',
})
const markers = ref([])

const initLongitudeAndLatitude = (longitude, latitude, address) => {
  myForm.longitude = longitude
  myForm.latitude = latitude
  myForm.address = address
  initAMap()
}

const initAMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: import.meta.env.VITE_AMAP_SECURITY_CODE,
  }
  AMapLoader.load({
    key: import.meta.env.VITE_AMAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.ToolBar', // 缩放控件
      'AMap.ControlBar', //方向控件
      'AMap.MapType', // 图层切换控件
      'AMap.Scale', // 比例尺控件
      'AMap.HawkEye', // 鹰眼控件
      // 'AMap.Geolocation', // 定位控件
      'AMap.Geocoder',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
    ],
  })
    .then((AMap) => {
      map.value = new AMap.Map('container', {
        // 设置地图容器id
        // viewMode: '3D', // 是否为3D地图模式
        zoom: 13, // 初始化地图级别
        center:
          myForm.longitude && myForm.latitude
            ? [Number(myForm.longitude), Number(myForm.latitude)]
            : [116.397428, 39.90923], // 初始化地图中心点位置
      })

      if (myForm.longitude && myForm.latitude)
        setMarker(Number(myForm.longitude), Number(myForm.latitude))
      else setMarker(116.397428, 39.90923)
      addPlugin()
      // getLocation();
      searchMap()
      // 监听鼠标点击事件
      //map.value.on("click", clickMapHandler);
    })
    .catch((e) => {
      console.log('error:', e)
    })
    .finally(() => {
      emit('success')
    })
}

const addPlugin = () => {
  const toolbar = new AMap.ToolBar() //创建工具条插件实例
  map.value.addControl(toolbar) //添加工具条插件到页面
  // 工具方向盘
  // const controlBar = new AMap.ControlBar()
  // map.value.addControl(controlBar)
  // 工具-图层切换控件
  // const mapType = new AMap.MapType()
  map.value.addControl(mapType)
  // 工具-比例尺
  const scale = new AMap.Scale()
  map.value.addControl(scale)
  // 工具-鹰眼控件
  // const hawkEye = new AMap.HawkEye()
  map.value.addControl(hawkEye)
  // 工具-定位控件
  // const geolocation = new AMap.Geolocation()
  // map.value.addControl(geolocation)
}

const getLocation = () => {
  let companyId = props.companyId || route.params.cId || route.query.id
  if (!companyId) {
    const userStore = useUserStore()
    const userInfo = userStore.getUserInfo || { companyId: 0 }
    companyId = userInfo.companyId
  }
  // GetCompanyById(companyId).then(res => {
  //   if (res.code == 20000) {
  //     id.value = res.data.id
  //     if (res.data.longitude != '' && res.data.latitude != '') {
  //       getLocationByPoint(res.data.longitude, res.data.latitude)
  //       myForm.longitude = res.data.longitude
  //       myForm.latitude = res.data.latitude
  //     } else if (res.data.companyAddress != '') {
  //       getLocationByAddress(res.data.companyAddress)
  //     }
  //   }
  // })
}

const getLocationByAddress = (address) => {
  const geocoder = new AMap.Geocoder({
    radius: 1000,
    extensions: 'all',
  })
  geocoder.getLocation(address, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      myForm.longitude = result.geocodes[0].location.lng
      myForm.latitude = result.geocodes[0].location.lat
      map.value.setCenter(result.geocodes[0].location)
      addMarker(myForm.longitude, myForm.latitude, address)
      //addContent(address);
    } else {
      console.error('地址查询失败:', result.info)
    }
  })
}

const getLocationByPoint = (lng, lat) => {
  console.log(lng, lat)
  if (lng && lat) {
    const geocoder = new AMap.Geocoder({
      radius: 1000,
      extensions: 'all',
    })
    let that = this
    // var lnglat = [110.41366,21.215599]
    var lnglat = [lng, lat]
    geocoder.getAddress(lnglat, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        console.log('result', result)
        myForm.address = result.regeocode.formattedAddress

        map.value.setCenter(lnglat)
        map.value.setZoom(18)
        addMarker(lng, lat, myForm.address)
        //addContent(address);
      } else {
      }
    })
  }
}

// 关键字查询
const searchMap = () => {
  // 搜索框自动完成类
  auto.value = new AMap.AutoComplete({
    input: 'tipinput', // 使用联想输入的input的id
  })
  //构造地点查询类
  placeSearch.value = new AMap.PlaceSearch({
    map: map.value,
  })
  // 当选中某条搜索记录时触发
  auto.value.on('select', selectSite)
}

//选中查询出的记录
const selectSite = (e) => {
  if (e.poi.location) {
    const lnglat = [e.poi.location.lng, e.poi.location.lat]
    placeSearch.value.setCity(e.poi.adcode)
    placeSearch.value.search(e.poi.name, () => {
      placeSearch.value.clear()
    }) //关键字查询
    myForm.address = e.poi.name
    myForm.longitude = e.poi.location.lng
    myForm.latitude = e.poi.location.lat
    map.value.setCenter(lnglat)

    const geocoder = new AMap.Geocoder({})
    geocoder.getAddress(lnglat, function (status, result) {
      console.log('result', result)
      if (status === 'complete' && result.regeocode) {
        addMarker(myForm.longitude, myForm.latitude, myForm.address)
      }
    })
  } else {
    console.error('查询地址失败，请重新输入地址')
  }
}

const addMarker = (lng, lat, address) => {
  removeMarker()

  marker.value = new window.AMap.Marker({
    position: [lng, lat],
  })
  marker.value.setMap(map.value) //放在map这个对象里面
  markers.value.push(marker.value)
  //顺便新增一个点击标记点出来的窗口
  infoWindow.value = new window.AMap.InfoWindow({
    content: '公司地址:<br>' + address, // 添加你想要显示的文字描述
  })

  // 点击标记点时显示信息窗体
  marker.value.on('click', () => {
    infoWindow.value.open(map.value, marker.value.getPosition())
  })
}

// 点击地图事件获取经纬度，并添加标记
const clickMapHandler = (e) => {
  const lnglat = [e.lnglat.getLng(), e.lnglat.getLat()]
  setMarker(lnglat)
  // 点击地图上的位置，根据经纬度转换成详细地址
  const geocoder = new AMap.Geocoder({})
  geocoder.getAddress(lnglat, function (status, result) {
    if (status === 'complete' && result.regeocode) {
      myForm.address = result.regeocode.formattedAddress
    }
  })
}

//  添加标记
const setMarker = (longitude, latitude) => {
  removeMarker()

  const icon = new AMap.Icon({
    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png', // Icon的图像
    size: new AMap.Size(28, 36), // 图标尺寸
    imageSize: new AMap.Size(28, 36), // 根据所设置的大小拉伸或压缩图片
  })

  const marker = new AMap.Marker({
    position: new AMap.LngLat(longitude, latitude),
    offset: new AMap.Pixel(-14, -36),
    icon: icon,
  })
  if (myForm.address) {
    console.log(myForm.address)
    marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, -5), //设置文本标注偏移量
      content: `<div class='info'>${myForm.address}</div>`, //地址
    })
  }

  map.value.add(marker)
  emit('success')
}

// 删除之前后的标记点
const removeMarker = () => {
  if (markers.value) {
    map.value.remove(markers.value)
  }
}

const onSubmit = () => {
  // AddCompanyInfo({
  //   id: id.value, // 公司名称(注册),当地政府等级的商业机构名称
  //   longitude: myForm.longitude, // 公司营业执照注册所在国家
  //   latitude: myForm.latitude, // 经营模式(1: 生产工厂; 2: 经销批发; 3: 商业服务; 4: 招商代理; 5: 其他)
  // }).then((res) => {
  //   if (res.code === 20000) {
  //     ElMessage.success(res.message)
  //   }
  // })
}

const onSearch = () => {
  getLocationByAddress(myForm.address)
}

// onMounted(() => {
//   initAMap()
// })

onUnmounted(() => {
  map.value?.destroy()
})

defineExpose({
  initLongitudeAndLatitude,
})
</script>

<style scoped>
#container {
  width: 100%;
  height: 400px;
}
.latlng {
  padding: 20px;
}
.amap-logo {
  display: none;
  opacity: 0 !important;
}
.amap-copyright {
  opacity: 0;
}
.search_box {
  padding: 20px;
}
/* ::v-deep .amap-icon img {
  width: 25px;
  height: 34px;
} */
:deep .amap-logo {
  display: none !important;
}
</style>
